package com.test1.administrator.website;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.Window;

import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.test1.administrator.website.dao.DBOperator;
import com.test1.administrator.website.entity.Website;
import com.test1.administrator.website.util.websiteIsNullException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private List<Map<String, Website>> mData;
    DBOperator dbOperator;
    MyAdapter adapter;
    public static final int SEND=5;
    int[] send_position;
    BottomPopView mWindow;




    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent netIntent=new Intent(this,NetService.class);
        stopService(netIntent);
        Log.v("Main","stopService");
        if(mWindow!=null) {
            if (mWindow != null || mWindow.conn != null)
                unbindService(mWindow.conn);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);



        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        ListView sitelist=(ListView)findViewById(R.id.sitelist);

//        启动服务器
                Intent netIntent=new Intent(MainActivity.this,NetService.class);
                startService(netIntent);
                Log.v("Main","startService");

        mData=getData();
        adapter=new MyAdapter(this);
        sitelist.setAdapter(adapter);


        sitelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(adapter.getItemText(position).getSite())));
            }
        });


        sitelist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i=new Intent(MainActivity.this,WebSiteEdit.class);
                i.putExtra("position",position);
                startActivityForResult(i,1);
//                adapter.removeWebsite(position);
                return true;
            }
        });


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                try {
//                    Website a=new Website("111","https://www.baidu.com");
//                    adapter.addWebsite(a);
                    Intent i=new Intent(MainActivity.this,WebSiteEdit.class);
                    startActivityForResult(i,1);


//                } catch (websiteIsNullException e) {
//                    e.printStackTrace();
//                    Snackbar.make(view, "Add failed", Snackbar.LENGTH_LONG)
//                            .setAction("Action", null).show();
//                }
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
            }
        });



    }

    /**
     * Dispatch incoming result to the correct fragment.
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode){
            case 1:
                mData=getData();
                adapter.notifyDataSetChanged();
                break;
            case SEND:
                send_position=data.getIntArrayExtra("send");
//            send_id 获取website
                for(Integer web_id:send_position){
                    //            取出list数据
                    Log.v("web_id","-----------------------------"+web_id);
                    Set sData=mData.get(web_id).keySet();
                    String id=(String)sData.iterator().next();
                    Website website=mData.get(web_id).get(id);
//                发送website
                    mWindow.clientService.sendMessage(website.toString());
                }
//                unbindService(mWindow.conn);
                break;


        }
    }

    public List<Map<String,Website>> getData(){
        dbOperator=new DBOperator(MainActivity.this);
        List<Map<String,Website>> list=dbOperator.query();
        return list;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {


            ViewGroup viewGroup=(ViewGroup) findViewById(R.id.fab).getParent();
            viewGroup.removeView(findViewById(R.id.fab));

            mWindow=new BottomPopView(this,findViewById(R.id.sitelist)) {
                /**
                 * 第一个按钮被点击的回调
                 */
                @Override
                public void onTopButtonClick() {

                }


//                /**
//                 * 第二个按钮被点击的回调
//                 */
//                @Override
//                public void onBottomButtonClick() {
//
//                }

            };

            mWindow.setTopText("发送给");
            mWindow.show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



        public final class ViewHolder{
        public TextView info;
        public Button edit;
    }


    public class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MyAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        public void addWebsite(Website website){
            Map<String,String> map=new HashMap<>();
            map.put(website.getName(),website.getSite());
            dbOperator.insert(website.getName(),website.getSite());
            mData=getData();
            notifyDataSetChanged();
        }

        public void removeWebsite(int position){
            String id=mData.get(position).keySet().iterator().next();
            mData.remove(position);
            dbOperator.delete(id);
            notifyDataSetChanged();
        }

        public Website getItemText(int position){
            return mData.get(position).get(mData.get(position).keySet().iterator().next());
        }
        /**
         * How many items are in the data set represented by this Adapter.
         *
         * @return Count of items.
         */
        @Override
        public int getCount() {
            return mData.size();
        }

        /**
         * Notifies the attached observers that the underlying data has been changed
         * and any View reflecting the data set should refresh itself.
         */
        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
        }

        /**
         * Get the data item associated with the specified position in the data set.
         *
         * @param position Position of the item whose data we want within the adapter's
         *                 data set.
         * @return The data at the specified position.
         */
        @Override
        public Object getItem(int position) {
            return null;
        }

        /**
         * Get the row id associated with the specified position in the list.
         *
         * @param position The position of the item within the adapter's data set whose row id we want.
         * @return The id of the item at the specified position.
         */
        @Override
        public long getItemId(int position) {
            return position;
        }

        /**
         * Get a View that displays the data at the specified position in the data set. You can either
         * create a View manually or inflate it from an XML layout file. When the View is inflated, the
         * parent View (GridView, ListView...) will apply default layout parameters unless you use
         * {@link LayoutInflater#inflate(int, ViewGroup, boolean)}
         * to specify a root view and to prevent attachment to the root.
         *
         * @param position    The position of the item within the adapter's data set of the item whose view
         *                    we want.
         * @param convertView The old view to reuse, if possible. Note: You should check that this view
         *                    is non-null and of an appropriate type before using. If it is not possible to convert
         *                    this view to display the correct data, this method can create a new view.
         *                    Heterogeneous lists can specify their number of view types, so that this View is
         *                    always of the right type (see {@link #getViewTypeCount()} and
         *                    {@link #getItemViewType(int)}).
         * @param parent      The parent that this view will eventually be attached to
         * @return A View corresponding to the data at the specified position.
         */
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if(convertView==null){

                holder=new ViewHolder();



                convertView=mInflater.inflate(R.layout.sitelayout,null);
                holder.info=(TextView)convertView.findViewById(R.id.info);
                holder.edit=(Button)convertView.findViewById(R.id.edit);


//                注意：button会抢夺listview焦点
                holder.edit.setFocusable(false);
                convertView.setTag(holder);


            }else{

                holder=(ViewHolder)convertView.getTag();
            }


//            取出list数据
            Set sData=mData.get(position).keySet();
            String id=(String)sData.iterator().next();
            Website website=mData.get(position).get(id);

            holder.info.setText(website.getName()+"    "+website.getSite());

            holder.edit.setText("删除");
            holder.edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    removeWebsite(position);

//                    BottomPopView mPopView=new BottomPopView(MainActivity.this,v) {
//                        @Override
//                        public void onTopButtonClick() {
//
//                        }
//
//                        @Override
//                        public void onBottomButtonClick() {
//
//                        }
//                    };
//                    mPopView.setTopText("编辑");
//                    mPopView.setBottomText("打开链接");
//                    mPopView.show();
//
//
                }
            });
            return convertView;
        }

    }


    /**
     * 封装PopWindow
     *
     */

    public abstract class BottomPopView {
        private Context mContext;
        private View anchor;
        private LayoutInflater mInflater;
        private TextView mTvTop;
        private TextView mTvBottom;
        private TextView mTvCancel;
        private PopupWindow mPopupWindow;
        WindowManager.LayoutParams params;
        WindowManager windowManager;
        Window window;
        EditText hostText;
        Button mOkButton;
        ClientService clientService;

        private ServiceConnection conn=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                clientService=((ClientService.ServiceBinder)service).getService();
//                clientService.sendMessage("----------------从客户端发送的信息");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                clientService=null;
            }
        };


        /**
         * @param context
         * @param anchor  依附在哪个View下面
         */
        public BottomPopView(Activity context, View anchor) {
            this.mContext = context;
            this.mInflater = LayoutInflater.from(context);
            this.anchor = anchor;
            windowManager = context.getWindowManager();
            window = context.getWindow();
            params = context.getWindow().getAttributes();
            init();
        }

        public void init() {
            View view = mInflater.inflate(R.layout.bottom_pop_window, null);
            params.dimAmount = 0.5f;
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//            mTvBottom = (TextView) view.findViewById(R.id.tv_choose_photo);
            mTvTop = (TextView) view.findViewById(R.id.tv_take_photo);
//            mTvCancel = (TextView) view.findViewById(R.id.tv_cancel);
            hostText=(EditText)view.findViewById(R.id.host);
            mOkButton=(Button)view.findViewById(R.id.button2);

            mOkButton.setOnClickListener(new View.OnClickListener(){

                /**
                 * Called when a view has been clicked.
                 *
                 * @param v The view that was clicked.
                 */
                @Override
                public void onClick(View v) {
                    send(v);
                }
            });



            mTvTop.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    onTopButtonClick();
                }
            });
//            mTvBottom.setOnClickListener(new View.OnClickListener() {
//
//                @Override
//                public void onClick(View arg0) {
//                    // TODO Auto-generated method stub
//                    onBottomButtonClick();
//                }
//            });
//            mTvCancel.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    dismiss();
//                }
//            });

            mPopupWindow = new PopupWindow(view,windowManager.getDefaultDisplay().getWidth(), LinearLayout.LayoutParams.WRAP_CONTENT);
            //监听PopupWindow的dismiss，当dismiss时屏幕恢复亮度
            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    params.alpha = 1.0f;
                    window.setAttributes(params);
                }
            });
            mPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            mPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mPopupWindow.setTouchable(true);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            // 动画效果 从底部弹起
            mPopupWindow.setAnimationStyle(R.style.popWindow_animation);
        }

        /**
         * 显示底部对话框
         */
        public void show() {
            mPopupWindow.showAtLocation(anchor, Gravity.BOTTOM, 0, 0);
//            params.alpha = 0.5f;
            window.setAttributes(params);
        }

        /**
         * 第一个按钮被点击的回调
         */
        public abstract void onTopButtonClick();

        /**
         * 第二个按钮被点击的回调
         */
//        public abstract void onBottomButtonClick();

        /**
         * 确定按钮 回调
         * @param view
         */
        public void send(View view){
            String hostName=hostText.getText().toString();
//          启动客户端
            Intent i=new Intent(MainActivity.this,ClientService.class);
            i.putExtra("hostName",hostName);
            bindService(i,conn,BIND_AUTO_CREATE);

//            clientService.sendMessage("----------------从客户端发送的信息");
            Log.v("hostName",hostName);
            dismiss();

//            打开send website activity
            Intent send=new Intent(MainActivity.this,SendWebSite.class);
            startActivityForResult(send,SEND);

        }



        public void setTopText(String text) {
            mTvTop.setText(text);
        }

//        public void setBottomText(String text) {
//            mTvBottom.setText(text);
//        }
        public void dismiss(){
            if(mPopupWindow!=null && mPopupWindow.isShowing()){
                mPopupWindow.dismiss();
            }
        }
    }




}
